package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-10-19 09:56
 **/
public class LeetCode18 {

    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> list = new ArrayList<>();
        if (nums.length < 4) {
            return list;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < nums.length - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                for (int k = j + 1; k < nums.length - 1; k++) {
                    if (k > j + 1 && nums[k] == nums[k - 1]) {
                        continue;
                    }
                    int n = nums.length - 1;
                    while (n > k && nums[i] + nums[j] + nums[k] + nums[n] > target) {
                        n--;
                    }
                    if (n == k) {
                        break;
                    }
                    if (nums[i] + nums[j] + nums[k] + nums[n] == target) {
                        list.add(Arrays.asList(nums[i], nums[j], nums[k], nums[n]));
                    }
                }
            }
        }
        return list;
    }

}
